﻿using SlimDX;
using SlimDX.Direct3D9;
using System;
using System.Drawing;
using System.IO;

namespace SlimDXSample
{
    class Fader : IDisposable
    {
        public Device device;

        public bool isFading;
        public bool fading_in;
        public float fadetime;
        float alpha;
        Matrix Projection;
        VertexBuffer vertices;

        public Fader(Device device)
        {
            this.device = device;

            vertices = VertexHelper.BillBoardColoredVertexBuffer(device);

            SetAlpha(1.0f);
            isFading = true;
            fading_in = true;
            fadetime = 2.00f;

            Projection = Matrix.OrthoLH(2.0f, 2.0f, 0.0f, 1.0f);
        }

        public void Dispose()
        {
            vertices.Dispose();
            GC.SuppressFinalize(this);
        }

        public void Draw(float frameDelta)
        {
            if (alpha == 0.0f && isFading == false)
                return;

            // Orthographic projection
            device.SetTransform(TransformState.Projection, Projection);
            device.SetTransform(TransformState.World, Matrix.Identity);
            device.SetTransform(TransformState.View, Matrix.Identity);

            device.SetRenderState(RenderState.Lighting, false);
            VertexHelper.DrawColored(vertices);

            if (isFading)
            {
                if (fadetime == 0.0f)
                {
                    alpha = 0.0f;
                }
                else if (fading_in)
                {
                    alpha -= frameDelta / fadetime;
                    if (alpha < 0.0f)
                    {
                        alpha = 0.0f;
                        isFading = false;
                    }
                }
                else
                {
                    alpha += frameDelta / fadetime;
                    if (alpha > 1.0f)
                    {
                        alpha = 1.0f;
                        isFading = false;
                    }
                }
                SetAlpha(alpha);
            }
        }

        public void SetAlpha(float alpha)
        {
            DataStream ds = vertices.Lock(0, 64, LockFlags.None);
            byte bAlpha = (byte)(alpha * 255.0f);
            this.alpha = alpha;

            ds.Seek(15, SeekOrigin.Begin);
            ds.WriteByte(bAlpha);
            ds.Seek(31, SeekOrigin.Begin);
            ds.WriteByte(bAlpha);
            ds.Seek(47, SeekOrigin.Begin);
            ds.WriteByte(bAlpha);
            ds.Seek(63, SeekOrigin.Begin);
            ds.WriteByte(bAlpha);

            vertices.Unlock();
        }
    }
}
